import React from 'react';
import { DndProvider } from 'react-dnd';
import HTML5Backend from 'react-dnd-html5-backend';
import { Drawer, Button, Table } from 'antd';
import { ColumnProps } from 'antd/es/table';

import DragableBodyRow, { handleMoveRow } from '@/components/TableConfig/DragableBodyRow';
import styles from './index.less';

interface ConfigTypes {
  columns: ColumnProps<any>[];
}

interface Props {
  config: ConfigTypes;
  drawerVisible: boolean;
  onDrawerClose: () => void;
  onConfigChange: (config: ConfigTypes) => void;
}

const configColumns = [
  {
    title: '标题',
    dataIndex: 'title',
    key: 'title',
  },
  {
    title: '宽度',
    dataIndex: 'width',
    key: 'width',
  },
];

const TableConfig: React.FC<Props> = props => {
  const { config, drawerVisible, onDrawerClose, onConfigChange } = props;
  const { columns } = config;

  const rowSelection = {
    selectedRowKeys: columns.filter((col: any) => !col.hidden).map((col: any) => col.key),
    onChange: (selectedRowKeys: string[] | number[]) => {
      const newColumns = columns.map((col: any) => ({
        ...col,
        hidden: selectedRowKeys.indexOf(col.key) < 0,
      }));
      onConfigChange({ columns: newColumns });
    },
    getCheckboxProps: (record: any) => ({ disabled: record.disabled }),
  };

  const moveRow = (dragIndex: number, hoverIndex: number) => {
    const newData = handleMoveRow(columns, dragIndex, hoverIndex);
    onConfigChange({ columns: newData });
  };

  return (
    <Drawer
      title="自定义表格"
      width={400}
      destroyOnClose
      visible={drawerVisible}
      onClose={onDrawerClose}
    >
      <DndProvider backend={HTML5Backend}>
        <Table
          className={styles.tableDragSorting}
          size="middle"
          bordered
          components={{ body: { row: DragableBodyRow } }}
          columns={configColumns}
          dataSource={columns}
          rowKey="key"
          rowSelection={rowSelection}
          pagination={false}
          onRow={(record, index) => ({ index, moveRow })}
        />
      </DndProvider>
      <div className={styles.drawerFooter}>
        <Button type="primary" onClick={onDrawerClose}>
          重置
        </Button>
        <Button style={{ marginLeft: 8 }} onClick={onDrawerClose}>
          关闭
        </Button>
      </div>
    </Drawer>
  );
};

export default TableConfig;
